/**
 * 
 */
package com.android.gtdroid;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;

/**
 * @author xiang
 *
 */
public class ContextAct extends Activity {
	
	private final String[] fromCols = new String[] {
			"item_name",
			"item_context",
			"item_pos",
			"item_tags"};
	private final int[] toLayouts = new int[] {
			R.id.tv_task,
			R.id.tv_row_context,
			R.id.tv_row_pos,
			R.id.tv_row_tag};
	private final String TAG = "ContextAct";
	
	private ExpandableListView elvContext;
	private MySimpleExpandableListAdapter msela;
	private ArrayList<HashMap<String, Object>> groups = new ArrayList<HashMap<String, Object>>();
	private ArrayList<ArrayList<HashMap<String, Object>>> children =
			new ArrayList<ArrayList<HashMap<String, Object>>>();
	private GTDApp ga;
	private long posInTable;
	private HashMap<String, Object> hmSelected;
	private boolean mIsCollapse = false;
	private ArrayList<Boolean> mExpandGroup;
	private boolean mIsTitleClick = false;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Log.e(TAG, "onCreate Method is called!");
		
		setContentView(R.layout.panel_context);
		
		elvContext = (ExpandableListView) findViewById(R.id.elv_context);
		
		handleEvent();
		
		ga = (GTDApp) getApplication();
		
		msela = new MySimpleExpandableListAdapter(
				ContextAct.this,
				C.ADAPTER.CONTEXT,
				groups,
				R.layout.grp_context,
				new String[] { "group_name", "child_count" },
				new int[] { R.id.tv_context_group, R.id.tv_context_count },
				children,
				R.layout.row_task,
				fromCols,
				toLayouts);
		elvContext.setAdapter(msela);
		
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		Log.e(TAG, "onStart is called!");
		
		
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		
		Log.e(TAG, "onRestart is called!");
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.e(TAG, "onResume is called!");
		
		updateContextData();		// when switched to context, onResume method is called
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		Log.e(TAG, "onStop is called!");
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		Log.e(TAG, "onPause is called!");
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		Log.e(TAG, "onPause is called!");
	}
	
	private void updateContextData() {
		ArrayList<HashMap<String,Object>> items = null;
		HashMap<String, Object> hm;
		Cursor taskCursor = null;
		ArrayList<String> al = null;
		int size;
		int[] index;
		
		groups.clear();
		for (int i=0; i<children.size(); i++)
			children.get(i).clear();
		children.clear();
		
		al = ga.getContexts();
		
		size = al.size();
		index = new int[size];
		for (int i=0; i<size-1; i++)
			index[i] = i+1;
		index[size-1] = 0;
		
		// default is collapsing all groups
		mExpandGroup = new ArrayList<Boolean>();
		for (int i=0; i<size; i++)
			mExpandGroup.add(new Boolean(true));
		
		for (int i : index) {
			String sql = "select * from " + ga.getDbta().getTableName()
					+ " where " + DBTaskAdapter.KEY_CONTEXT + "=\"" + al.get(i)
					+ "\" AND " + DBTaskAdapter.KEY_COMPLETED + "=" + C.TASK.UNCOMPLETED
					/*+ " AND " + DBTaskAdapter.KEY_LIST + "=\"" + list + "\""*/
					+ " order by task_created desc";
			taskCursor = ga.getDbta().excuteSQL(sql);
//			if (taskCursor.getCount() == 0)
//				continue;
			
			hm = new HashMap<String, Object>();
			hm.put("group_name", al.get(i));
			hm.put("child_count", (new Integer(taskCursor.getCount())).toString());
			groups.add(hm);
			
			Log.e(TAG, "number of context "+al.get(i)+": "+taskCursor.getCount());
			
			items = new ArrayList<HashMap<String, Object>>();
			fillArray(taskCursor, items);
			children.add(items);
		}
		
		for (int i=0; i<groups.size(); i++)
			elvContext.expandGroup(i);
		
		msela.notifyDataSetChanged();
	}
	
	/**
	 * fill array $item with the specific condition
	 * @param taskCursor
	 */
	private void fillArray(Cursor taskCursor, ArrayList<HashMap<String, Object>> items) {
		HashMap<String, Object> hm;
		
		if (taskCursor.moveToFirst()) {
			do {
				long rowId = taskCursor.getLong(DBTaskAdapter.COL_ID);
				String task = taskCursor.getString(DBTaskAdapter.COL_TASK_NAME);
				String note = taskCursor.getString(DBTaskAdapter.COL_TASK_NOTE);
				String list = taskCursor.getString(DBTaskAdapter.COL_TASK_LIST);
				
				String ctt = taskCursor.getString(DBTaskAdapter.COL_TASK_CONTEXT);
				String prj = taskCursor.getString(DBTaskAdapter.COL_TASK_PROJECT);
				String pos = taskCursor.getString(DBTaskAdapter.COL_TASK_POS);
				
				int status = taskCursor.getInt(DBTaskAdapter.COL_TASK_STATUS);
				String st = taskCursor.getString(DBTaskAdapter.COL_TASK_ST);
				String et = taskCursor.getString(DBTaskAdapter.COL_TASK_ET);
				String repeat = taskCursor.getString(DBTaskAdapter.COL_TASK_REPEAT);
				String remind = taskCursor.getString(DBTaskAdapter.COL_TASK_REMIND);
				
				String prior = taskCursor.getString(DBTaskAdapter.COL_TASK_PRIOR);
				String tags = taskCursor.getString(DBTaskAdapter.COL_TASK_TAG);
				String created = taskCursor.getString(DBTaskAdapter.COL_TASK_CREATED);
				int completed = taskCursor.getInt(DBTaskAdapter.COL_TASK_COMPLETED);
				
				
				hm = new HashMap<String, Object>();
				hm.put("item_id", rowId);
				hm.put("item_name", task);
				hm.put("item_note", note);
				hm.put("item_list", list);
				
				hm.put("item_context", ctt);
				hm.put("item_project", prj);
				hm.put("item_pos", pos);
				
				hm.put("item_status", status);
				hm.put("item_st", st);
				hm.put("item_et", et);
				hm.put("item_repeat", repeat);
				hm.put("item_remind", remind);
				
				hm.put("item_prior", prior);
				hm.put("item_tags", tags);
				hm.put("item_created", created);
				hm.put("item_completed", completed);
				
				items.add(hm);
			} while (taskCursor.moveToNext());
		}
	}
	
	private void handleEvent() {
		elvContext.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				hmSelected = (HashMap<String, Object>) children.get(groupPosition).get(childPosition);
				posInTable = (Long) hmSelected.get("item_id");
				
				String list = (String) hmSelected.get("item_list");
				int listIndex = ga.lists.indexOf(list);
				
//				Log.e(tag, "listIndex is: "+listIndex);
				
				Intent itt = new Intent(ContextAct.this, TaskDetailAct.class);
				
				itt.putExtra("row_id", posInTable);
				itt.putExtra("selected_task", hmSelected);
				itt.putExtra("list_index", listIndex);	
				itt.putExtra("task_status", C.TASK.UNCOMPLETED);
				
				startActivity(itt);
				return false;
			}
		});
		
		/*elvContext.setOnGroupClickListener(new OnGroupClickListener() {
			
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				boolean expanded = elvContext.isGroupExpanded(groupPosition);
				if (expanded)
					mExpandGroup.set(groupPosition, new Boolean(false));
				else
					mExpandGroup.set(groupPosition, new Boolean(true));
				
				return false;
			}
		});*/
		
		elvContext.setOnGroupExpandListener(new OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int groupPosition) {
				// TODO Auto-generated method stub
				if (!mIsTitleClick) {
					mExpandGroup.set(groupPosition, new Boolean(true));
					mIsCollapse = false;
				}
				
				
			}
		});
		elvContext.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			@Override
			public void onGroupCollapse(int groupPosition) {
				// TODO Auto-generated method stub
				if (!mIsTitleClick) {
					mExpandGroup.set(groupPosition, new Boolean(false));
					mIsCollapse = false;
				}
			}
		});
		
		TextView tvContext = (TextView) getParent().findViewById(R.id.tv_context_title);
		tvContext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				for (int i=0; i<groups.size(); i++)
					Log.e(TAG, "groups["+i+"]: "+mExpandGroup.get(i)+"\n");
				
				mIsTitleClick = true;
				
				if (mIsCollapse) {		// expand groups to their previous state
					mIsCollapse = false;
					
					for (int i=0; i<groups.size(); i++) {
						if (mExpandGroup.get(i).booleanValue())
							elvContext.expandGroup(i);
						else
							elvContext.collapseGroup(i);
					}
				} else {	// collapse groups
					mIsCollapse = true;
					
					for (int i=0; i<groups.size(); i++)
						elvContext.collapseGroup(i);
				}
				
				mIsTitleClick = false;
			}
		});
	}
}
